<template>
  <zeda-dialog
    v-model="visible"
    :title="title"
    width="600px"
    :before-close="handleClose"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <form-button
      slot="footer"
      :loading="loading"
      @cancel="handleClose"
      @submit="submit"
    >
    </form-button>
  </zeda-dialog>
</template>

<script>
import { addRole, editRole, getRole, getRoleArr } from "@/api/auth/index.js";

import FormButton from "@/components/FormButton";

export default {
  dicts: ["energy_type"],
  components: {
    FormButton,
  },
  props: {
    id: {
      type: [Number, String],
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
    disabledFalge: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      loading: false, // 按钮加载中判断
      checked: false, // 是否启用复制角色权限
      roleArr: [],
      apsForm: {
        formRef: "form",
        formData: {},
        formConfig: {
          formAttr: {
            // inline: true,
            "label-position": "right",
            size: "small",
            bsColumn: {
              col: 1,
              middle: true,
            },
            rules: {
              roleName: [
                {
                  required: true,
                  message: "角色名称不能为空",
                  trigger: "blur",
                },
                {
                  validator: function (rule, value, callback) {
                    let reg = new RegExp(
                      "^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$"
                    );
                    if (!reg.test(value)) {
                      callback("请勿输入特殊字符，且不能以下划线开头和结尾");
                    } else {
                      callback();
                    }
                  },
                  trigger: "blur",
                },
              ],
              roleSort: [
                {
                  required: true,
                  message: "角色顺序不能为空",
                  trigger: "blur",
                },
              ],
            },
          },
          properties: {
            roleName: {
              label: "角色名称",
              typeName: "el-input",
            },
            roleSort: {
              label: "显示排序",
              render: (h) => {
                let that = this;
                let valNum = that.$refs?.form?.getFieldsValue().roleSort;
                let a = (
                  <el-input-number
                    v-model={valNum}
                    controls-position="right"
                    min={0}
                    onInput={(value) => {
                      that.$refs?.form?.setFieldValue("roleSort", value);
                    }}
                  ></el-input-number>
                );
                return a;
              },
            },
            remark: {
              label: "角色说明",
              typeName: "el-input",
              type: "textarea",
              rows: 4,
              placeholder: "请输入角色说明",
            },
            roleCopy: {
              label: "",
              display: true,
              render: (h) => {
                let that = this;
                let arr = [...that.roleArr];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().roleCopy;
                let checkBox = (
                  <el-checkbox v-model={that.checked}>复制</el-checkbox>
                );
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择角色",
                        value: valNum,
                        class: "role-select",
                        filterable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("roleCopy", value);
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: Number(value),
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                let b = <span>的角色权限</span>;
                return (
                  <div style="display:flex">
                    {checkBox}
                    {a}
                    {b}
                  </div>
                );
              },
            },
          },
        },
      },
    };
  },
  watch: {
    visible(value) {
      if (value) {
        this.apsForm.formConfig.properties.roleCopy.display =
          this.disabledFalge;
        // 新增
        if (!this.disabledFalge) {
          this.requestRoleArr();
        }
        if (String(this.id).length > 0) {
          this.getInfo();
        }
      }
    },
  },
  methods: {
    requestRoleArr() {
      this.roleArr = [];
      getRoleArr()
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.roles ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let obj = {
                label: item.roleName,
                value: item.roleId,
              };
              this.roleArr.push(obj);
            });
          }
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    getInfo() {
      getRole(this.id)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let newData = res?.data || {};
          this.$refs?.form?.setFieldsValue(newData);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    submit() {
      const data = {
        ...this.$refs.form.getFieldsValue(),
      };
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.id) {
            this.editRequest(data);
          } else {
            data.roleIds = [];
            if (this.checked) {
              if (String(data.roleCopy).length > 0) {
                data.roleIds.push(data.roleCopy);
              }
            }
            data.roleCopy = null;
            this.addRequest(data);
          }
        } else {
          return false;
        }
      });
    },
    addRequest(data) {
      addRole(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    editRequest(data) {
      editRole(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    handleClose(status) {
      this.checked = false;
      this.$refs["form"].resetFields();
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-form {
  .el-input,
  .el-cascader,
  .el-input-number,
  .el-select {
    width: 100% !important;
  }
  .role-select {
    width: 200px !important;
    margin: 0 20px;
  }
  .map {
    display: flex;
    .el-input {
      margin-right: 10px;
    }
  }
}
</style>
